<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="python," />




  


  <link rel="alternate" href="/atom.xml" title="理想-咸鱼" type="application/atom+xml" />






<meta name="description" content="tornado - 异步上下文管理（StackContext）初步使用1234567891011121314151617181920212223242526272829# -*- coding: utf-8 -*-import tornado.ioloopimport tornado.stack_contextioloop &#x3D; tornado.ioloop.IOLoop.instance()tim">
<meta property="og:type" content="article">
<meta property="og:title" content="tornado-异步上下文管理（StackContext）">
<meta property="og:url" content="http://yoursite.com/2018/10/17/tornado--yi-bu-shang-xia-wen-guan-li-%EF%BC%88stackcontext%EF%BC%89/index.html">
<meta property="og:site_name" content="理想-咸鱼">
<meta property="og:description" content="tornado - 异步上下文管理（StackContext）初步使用1234567891011121314151617181920212223242526272829# -*- coding: utf-8 -*-import tornado.ioloopimport tornado.stack_contextioloop &#x3D; tornado.ioloop.IOLoop.instance()tim">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-10-17T05:18:50.000Z">
<meta property="article:modified_time" content="2018-10-17T05:53:35.000Z">
<meta property="article:author" content="bigfish">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/10/17/tornado--yi-bu-shang-xia-wen-guan-li-（stackcontext）/"/>





  <title>tornado-异步上下文管理（StackContext） | 理想-咸鱼</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">理想-咸鱼</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">鱼翔浅底</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/10/17/tornado--yi-bu-shang-xia-wen-guan-li-%EF%BC%88stackcontext%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="bigfish">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="理想-咸鱼">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">tornado-异步上下文管理（StackContext）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-10-17T13:18:50+08:00">
                2018-10-17
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>  阅读数
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Words count in article&#58;</span>
                
                <span title="Words count in article">
                  918
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Reading time &asymp;</span>
                
                <span title="Reading time">
                  4
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="tornado-异步上下文管理（StackContext）"><a href="#tornado-异步上下文管理（StackContext）" class="headerlink" title="tornado - 异步上下文管理（StackContext）"></a>tornado - 异步上下文管理（StackContext）</h1><h2 id="初步使用"><a href="#初步使用" class="headerlink" title="初步使用"></a>初步使用</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"><span class="keyword">import</span> tornado.ioloop</span><br><span class="line"><span class="keyword">import</span> tornado.stack_context</span><br><span class="line"></span><br><span class="line">ioloop = tornado.ioloop.IOLoop.instance()</span><br><span class="line"></span><br><span class="line">times = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">callback</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'run callback'</span></span><br><span class="line">    <span class="keyword">raise</span> ValueError(<span class="string">'except in callback'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">async_task</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">global</span> times</span><br><span class="line">    times += <span class="number">1</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'run async task &#123;&#125;'</span>.format(times)</span><br><span class="line">    ioloop.add_callback(callback=callback)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        async_task()</span><br><span class="line">    <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">'main exception &#123;&#125;'</span>.format(e)</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'end'</span></span><br><span class="line"></span><br><span class="line">main()</span><br><span class="line">ioloop.start()</span><br></pre></td></tr></table></figure>

<p>异常没有在 main 中捕获：</p>
<pre><code>run async task 1
end
run callback
ERROR:root:Exception in callback &lt;function null_wrapper at 0x7f23ec300488&gt;
Traceback (most recent call last):
  File &quot;~/learn/tornado/tornado/ioloop.py&quot;, line 370, in _run_callback</code></pre><h2 id="包裹上下文"><a href="#包裹上下文" class="headerlink" title="包裹上下文"></a>包裹上下文</h2><p>使用 partial 生成新的函数, 最终调用的函数为 wrapper(callback)，在 wrapper 中捕获异常</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"><span class="keyword">import</span> tornado.ioloop</span><br><span class="line"><span class="keyword">import</span> tornado.stack_context</span><br><span class="line"><span class="keyword">import</span> functools</span><br><span class="line"></span><br><span class="line">ioloop = tornado.ioloop.IOLoop.instance()</span><br><span class="line"></span><br><span class="line">times = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">callback</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'run callback'</span></span><br><span class="line">    <span class="keyword">raise</span> ValueError(<span class="string">'except in callback'</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">wrapper</span><span class="params">(func)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        func()</span><br><span class="line">    <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">'main exception &#123;&#125;'</span>.format(e)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">async_task</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">global</span> times</span><br><span class="line">    times += <span class="number">1</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'run async task &#123;&#125;'</span>.format(times)</span><br><span class="line">    <span class="comment"># 使用 partial 生成新的函数</span></span><br><span class="line">    <span class="comment"># 最终 ioloop 调用的函数为 wrapper(callback)</span></span><br><span class="line">    ioloop.add_callback(callback=functools.partial(wrapper, callback))</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        async_task()</span><br><span class="line">    <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">'main exception &#123;&#125;'</span>.format(e)</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'end'</span></span><br><span class="line"></span><br><span class="line">main()</span><br><span class="line">ioloop.start()</span><br></pre></td></tr></table></figure>

<p>异常被正确捕获：</p>
<pre><code>run async task 1
end
run callback
main exception except in callback</code></pre><h2 id="使用-tornado-stack-context-例子"><a href="#使用-tornado-stack-context-例子" class="headerlink" title="使用 tornado stack_context 例子"></a>使用 tornado stack_context 例子</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"><span class="keyword">import</span> tornado.ioloop</span><br><span class="line"><span class="keyword">import</span> tornado.stack_context</span><br><span class="line"><span class="keyword">import</span> contextlib</span><br><span class="line"></span><br><span class="line">ioloop = tornado.ioloop.IOLoop.instance()</span><br><span class="line"></span><br><span class="line">times = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">callback</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'Run callback'</span></span><br><span class="line">    <span class="comment"># 抛出的异常在 contextor 中被捕获</span></span><br><span class="line">    <span class="keyword">raise</span> ValueError(<span class="string">'except in callback'</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">async_task</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">global</span> times</span><br><span class="line">    times += <span class="number">1</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'run async task &#123;&#125;'</span>.format(times)</span><br><span class="line">    <span class="comment"># add_callback, 会用之前保存的 (StackContext, contextor)，创建一个对象 StackContext(contextor)</span></span><br><span class="line">    <span class="comment"># ioloop 回调的时候使用 </span></span><br><span class="line">    <span class="comment"># with StackContext(contextor)</span></span><br><span class="line">    <span class="comment">#   callback</span></span><br><span class="line">    <span class="comment"># 从而 callback 函数也在 contextor 函数中执行，从而能够在 contextor 中捕获异常</span></span><br><span class="line">    <span class="comment"># 从而实现 async_task() 函数在 contextor 中执行，其引发的异常（其实是 callback）同时在 contextor 被捕获</span></span><br><span class="line">    ioloop.add_callback(callback=callback)</span><br><span class="line"></span><br><span class="line"><span class="meta">@contextlib.contextmanager</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">contextor</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'Enter contextor'</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">yield</span></span><br><span class="line">    <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">'Handler except'</span></span><br><span class="line">        <span class="keyword">print</span> <span class="string">'exception &#123;&#125;'</span>.format(e)</span><br><span class="line">    <span class="keyword">finally</span>:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">'Release'</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="comment">#使用StackContext包裹住contextor, 下面函数 async_task() 会在 contextor() 环境中执行</span></span><br><span class="line">    stack_context = tornado.stack_context.StackContext(contextor)</span><br><span class="line">    <span class="keyword">with</span> stack_context:</span><br><span class="line">        async_task()</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'End'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">main()</span><br><span class="line">ioloop.start()</span><br></pre></td></tr></table></figure>

<h3 id="tornado-stack-context-StackContext"><a href="#tornado-stack-context-StackContext" class="headerlink" title="tornado.stack_context.StackContext"></a>tornado.stack_context.StackContext</h3><p>tornado.stack_context 相当于一个上下文包裹器，它接收一个 context_factory 作为参数并保存<br>context_factory 是一个上下文类，拥有 <code>__enter__</code> <code>__exit__</code>方法</p>
<p>使用 with stack_context 时候，执行自己的 <code>__enter__</code><br><code>__enter__</code> 函数根据保存的 context_factory 创建一个 context 对象，并执行对象的 <code>__enter__</code>方法<br>StackContext 将 (StackContext, context_factory) 保存，将来执行回调的时候再创建一个 StackContext(context_factory) 来执行 call_back</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StackContext</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, context_factory)</span>:</span></span><br><span class="line">        self.context_factory = context_factory</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment"># contexts 入栈</span></span><br><span class="line">        self.old_contexts = _state.contexts</span><br><span class="line">        <span class="comment"># _state.contexts is a tuple of (class, arg) pairs</span></span><br><span class="line">        _state.contexts = (self.old_contexts + </span><br><span class="line">                           ((StackContext, self.context_factory),))</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            self.context = self.context_factory()</span><br><span class="line">            <span class="comment"># 进入 context 对象的执行环境</span></span><br><span class="line">            self.context.__enter__()</span><br><span class="line">        <span class="keyword">except</span> Exception:</span><br><span class="line">            _state.contexts = self.old_contexts</span><br><span class="line">            <span class="keyword">raise</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="keyword">return</span> self.context.__exit__(type, value, traceback)</span><br><span class="line">        <span class="keyword">finally</span>:</span><br><span class="line">            <span class="comment"># contexts 出栈</span></span><br><span class="line">            _state.contexts = self.old_contexts</span><br></pre></td></tr></table></figure>

<h3 id="IOLoop-add-callback"><a href="#IOLoop-add-callback" class="headerlink" title="IOLoop.add_callback"></a>IOLoop.add_callback</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_callback</span><span class="params">(self, callback)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> self._callbacks:</span><br><span class="line">        self._wake()</span><br><span class="line">        self._callbacks.append(stack_context.wrap(callback))</span><br></pre></td></tr></table></figure>

<h3 id="IOLoop-start"><a href="#IOLoop-start" class="headerlink" title="IOLoop.start"></a>IOLoop.start</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> self._stopped:</span><br><span class="line">        self._stopped = <span class="literal">False</span></span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    self._running = <span class="literal">True</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        <span class="comment"># Never use an infinite timeout here - it can stall epoll</span></span><br><span class="line">        poll_timeout = <span class="number">0.2</span></span><br><span class="line"></span><br><span class="line">        callbacks = self._callbacks</span><br><span class="line">        self._callbacks = []</span><br><span class="line">        <span class="keyword">for</span> callback <span class="keyword">in</span> callbacks:</span><br><span class="line">            <span class="comment"># 调用注册的 callback</span></span><br><span class="line">            self._run_callback(callback)</span><br></pre></td></tr></table></figure>

<h3 id="IOLoop-run-callback"><a href="#IOLoop-run-callback" class="headerlink" title="IOLoop._run_callback"></a>IOLoop._run_callback</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">_run_callback</span><span class="params">(self, callback)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        callback()</span><br><span class="line">    <span class="keyword">except</span> (KeyboardInterrupt, SystemExit):</span><br><span class="line">        <span class="keyword">raise</span></span><br><span class="line">    <span class="keyword">except</span>:</span><br><span class="line">        self.handle_callback_exception(callback)</span><br></pre></td></tr></table></figure>

<h3 id="stack-context-wrap"><a href="#stack-context-wrap" class="headerlink" title="stack_context.wrap"></a>stack_context.wrap</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">wrap</span><span class="params">(fn)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> fn <span class="keyword">is</span> <span class="literal">None</span> <span class="keyword">or</span> fn.__class__ <span class="keyword">is</span> _StackContextWrapper:</span><br><span class="line">        <span class="keyword">return</span> fn</span><br><span class="line">    <span class="comment"># functools.wraps doesn't appear to work on functools.partial objects</span></span><br><span class="line">    <span class="comment">#@functools.wraps(fn)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapped</span><span class="params">(callback, contexts, *args, **kwargs)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> contexts <span class="keyword">is</span> _state.contexts <span class="keyword">or</span> <span class="keyword">not</span> contexts:</span><br><span class="line">            callback(*args, **kwargs)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 包裹callback, 生成 StackContext(context_factory()) 对象</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> _state.contexts:</span><br><span class="line">            new_contexts = [cls(arg) <span class="keyword">for</span> (cls, arg) <span class="keyword">in</span> contexts]</span><br><span class="line"></span><br><span class="line">        <span class="keyword">elif</span> (len(_state.contexts) &gt; len(contexts) <span class="keyword">or</span></span><br><span class="line">            any(a[<span class="number">1</span>] <span class="keyword">is</span> <span class="keyword">not</span> b[<span class="number">1</span>]</span><br><span class="line">                <span class="keyword">for</span> a, b <span class="keyword">in</span> itertools.izip(_state.contexts, contexts))):</span><br><span class="line">            <span class="comment"># contexts have been removed or changed, so start over</span></span><br><span class="line">            new_contexts = ([NullContext()] +</span><br><span class="line">                            [cls(arg) <span class="keyword">for</span> (cls,arg) <span class="keyword">in</span> contexts])</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            new_contexts = [cls(arg)</span><br><span class="line">                            <span class="keyword">for</span> (cls, arg) <span class="keyword">in</span> contexts[len(_state.contexts):]]</span><br><span class="line">        <span class="keyword">if</span> len(new_contexts) &gt; <span class="number">1</span>:</span><br><span class="line">            <span class="keyword">with</span> _nested(*new_contexts):</span><br><span class="line">                callback(*args, **kwargs)</span><br><span class="line">        <span class="keyword">elif</span> new_contexts:</span><br><span class="line">            <span class="comment"># 执行 StackContext，调用 fn</span></span><br><span class="line">            <span class="keyword">with</span> new_contexts[<span class="number">0</span>]:</span><br><span class="line">                callback(*args, **kwargs)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            callback(*args, **kwargs)</span><br><span class="line">    <span class="comment"># 返回偏函数，绑定 fn, _state.contexts</span></span><br><span class="line">    <span class="keyword">return</span> _StackContextWrapper(wrapped, fn, _state.contexts)</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">_StackContextWrapper</span><span class="params">(functools.partial)</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>


<hr>
<p>Sync From: <a href="https://github.com/TheBigFish/blog/issues/1" target="_blank" rel="noopener">https://github.com/TheBigFish/blog/issues/1</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"># python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/01/python-json--xu-lie-hua-ji-fan-xu-lie-hua/" rel="prev" title="python json 序列化及反序列化">
                python json 序列化及反序列化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  
    <div id="gitalk-container"></div>
  


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">bigfish</p>
              <p class="site-description motion-element" itemprop="description">一些简单的想法</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#tornado-异步上下文管理（StackContext）"><span class="nav-number">1.</span> <span class="nav-text">tornado - 异步上下文管理（StackContext）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#初步使用"><span class="nav-number">1.1.</span> <span class="nav-text">初步使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#包裹上下文"><span class="nav-number">1.2.</span> <span class="nav-text">包裹上下文</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用-tornado-stack-context-例子"><span class="nav-number">1.3.</span> <span class="nav-text">使用 tornado stack_context 例子</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#tornado-stack-context-StackContext"><span class="nav-number">1.3.1.</span> <span class="nav-text">tornado.stack_context.StackContext</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IOLoop-add-callback"><span class="nav-number">1.3.2.</span> <span class="nav-text">IOLoop.add_callback</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IOLoop-start"><span class="nav-number">1.3.3.</span> <span class="nav-text">IOLoop.start</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IOLoop-run-callback"><span class="nav-number">1.3.4.</span> <span class="nav-text">IOLoop._run_callback</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#stack-context-wrap"><span class="nav-number">1.3.5.</span> <span class="nav-text">stack_context.wrap</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bigfish</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.3</div>




<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  








  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
  <div id="gitalk-container"></div>
  <script type="text/javascript">
    var gitalk = new Gitalk({
      clientID: '539ee569f1e8cf3ea34a',
      clientSecret: 'd4384d3c96e794fea423f52d48aec0caab7d0eea',
      repo: 'blog_comment',
      owner: 'TheBigFish',
      admin: ['TheBigFish'],
      id: location.pathname,
      distractionFreeMode: 'false'
    })
    gitalk.render('gitalk-container')
  </script>



  





  

  

  

  

  

  

</body>
</html>
